from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from .models import *
import jwt
from meiduo.settings import SECRET_KEY
from rest_framework.response import Response
# Create your views here.
class LoginView(APIView):
    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = UserModel.objects.filter(username=username,password=password).first()
        if user:
            info={
                'uid':user.id,
                'username':user.username
            }
            token = jwt.encode(info,SECRET_KEY)
            return Response({'msg': '登陆成功', "token":token})
        else:
            return Response({'msg':'登陆失败'}, status=401)

class TestView(APIView):
    def get(self,request):

        uid = request.COOKIES.get("uid")
        if uid:
            return Response({'msg':'令牌有效'})
        else:
            return Response({'msg':'令牌无效'},status=401)

    def post(self,request):
        uid = request.COOKIES.get("uid")
        if uid:
            return Response({'msg':'令牌有效'})
        else:
            return Response({'msg':'令牌无效'},status=401)